package net.awpspace.mobile.global;

import java.util.Vector;

import net.awpspace.mobile.management.book.BookModel;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

/**
 * JSON encoding/decoding utilities
 * 
 * @author Diep
 * 
 */
public class Encode {

	/**
	 * Message type
	 */
	public static final int LOGIN = 1;
	public static final int REGISTER = 2;
	public static final int LOAD = 3;
	public static final int UPDATE = 4;
	public static final int DELETE = 5;
	public static final int RESULT = 0;

	/**
	 * Get message type from communication message
	 * 
	 * @param source
	 *            json object message
	 * @return Encode type
	 */
	public static synchronized final int getType(String source) {
		try {
			JSONObject js = new JSONObject(source);
			return js.getInt("type");
		} catch (JSONException e) {
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * Get result from communication message
	 * 
	 * @param source
	 *            json object message
	 * @return true if result was ok, false if otherwise
	 */
	public static synchronized final boolean getResult(String source) {
		try {
			JSONObject js = new JSONObject(source);
			return "ok".equals(js.getString("result"));
		} catch (JSONException e) {
			return false;
		}
	}

	/**
	 * Get book list from communication message
	 * 
	 * @param source
	 * @return
	 */
	public static synchronized final Vector getBooks(String source) {
		Vector vector = new Vector();
		try {
			JSONArray array = (new JSONObject(source)).getJSONArray("books");
			if (array == null) {
				return null;
			}
			for (int i = 0; i < array.length(); ++i) {
				JSONObject object = new JSONObject(array.get(i).toString());
				String id = object.getString("id");
				String name = object.getString("name");
				String author = object.getString("author");
				String image = object.getString("image");
				String description = object.getString("description");
				vector.addElement(new BookModel(Integer.parseInt(id), name,
						author, image, description));
			}
			return vector;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Factory method for building communication message based on json structure
	 * 
	 * @param type
	 * @param tag
	 * @param data
	 * @return
	 */
	public static synchronized final byte[] build(int type, String[] tag,
			String[] data) {
		StringBuffer json = new StringBuffer();
		json.append("{\"type\":");
		json.append(type);
		if (tag != null && data != null) {
			for (int i = 0; i < tag.length; ++i) {
				json.append(",\"" + tag[i] + "\":");
				if (data[i] != null) {
					json.append('"' + data[i] + '"');
				} else {
					json.append("null");
				}
			}
		}
		json.append('}');
		return json.toString().getBytes();
	}
}
